#include "../include/Logger.h"
#include "../include/LoggingGlobal.h"
#include "../include/IHandler.h"
#include "../include/LogRecord.h"

namespace logging
{
    std::map<std::string, Logger*> Logger::m_loggerRegistry = std::map<std::string, Logger*>();

    Logger * Logger::getLogger( const std::string & name )
    {
	if( Logger::m_loggerRegistry[name] == 0 )
	    Logger::m_loggerRegistry[name] = new Logger( name );
	
	return( Logger::m_loggerRegistry[name] );
    }

    void Logger::log( LogLevel 			logLevel, 
		      const std::string & 	message,
		      const std::string & 	sourceFileName,
		      const std::string & 	sourceClassName,
		      const std::string & 	sourceMethodName,
		      int 			sourceFileLine
		      )	
    {
	if( logLevel < m_logLevel )
	    return;

	LogRecord record;
	record.m_logLevel 		= logLevel;
	record.m_message		= message;
	record.m_timeStamp 		= time( 0 );
	record.m_sequenceNumber 	= getSequenceNumber();
	record.m_sourceFileName 	= sourceFileName;
	record.m_sourceClassName 	= sourceClassName;
	record.m_sourceMethodName 	= sourceMethodName;
	record.m_line 			= sourceFileLine;
	
	for( unsigned i = 0; i < m_vHandlers.size(); i++ )
	    m_vHandlers[i]->processRecord( record );
    }

    void Logger::finest( const std::string & message )
    {
	log( Finest, 	     
	     message );
    }
    
    void Logger::finer( const std::string & message )
    {
	log( Finer, 	     
	     message );
    }

    void Logger::fine( const std::string & message )
    {
	log( Fine, 	     
	     message );
    }
    
    void Logger::config( const std::string & message )
    {
	log( Config, 	     
	     message );
    }

    void Logger::info( const std::string & message )
    {
	log( Info, 	     
	     message );
    }

    void Logger::warning( const std::string & message )
    {
	log( Warning, 	     
	     message );
    }

    void Logger::severe( const std::string & message )
    {
	log( Severe, 	     
	     message );
    }

    // IHandler Management
    void Logger::addHandler( IHandler * handler )
    {
	std::vector<IHandler*>::iterator it = std::find( m_vHandlers.begin(),
							 m_vHandlers.end(),
							 handler
							 );

	if( it == m_vHandlers.end() )
	    m_vHandlers.push_back( handler );
    }
    
    void Logger::removeHandler( IHandler * handler )
    {
	std::vector<IHandler*>::iterator it = std::find( m_vHandlers.begin(),
							 m_vHandlers.end(),
							 handler
							 );

	if( it != m_vHandlers.end() )
	    m_vHandlers.erase( it );	
    }

    bool Logger::hasHandler( IHandler * handler )
    {
	std::vector<IHandler*>::iterator it = std::find( m_vHandlers.begin(),
							 m_vHandlers.end(),
							 handler
							 );

	return( it != m_vHandlers.end() );
    }

    // Protected Constructor
    Logger::Logger( const std::string & name,
		    LogLevel logLevel ) : m_logLevel( logLevel ),
					   m_name( name )
					   
    {	
    }
}
